package com.example.oauth2server.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.oauth2server.user.domain.CustomUserDetail;
import com.example.oauth2server.user.domain.User;
import com.example.oauth2server.user.service.UserService;
import com.example.oauth2server.user.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 用户信息校验
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService, UserDetailsService {

    @Autowired
    private UserMapper userMapper;


    /**
     * 获取用户信息
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        if (StringUtils.isEmpty(username)) {
            log.warn("用户名不能为空 ! {}",username);
            throw new RuntimeException("用户名不能为空!");
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                    .eq(User::getUsername,username);
        User user = userMapper.selectOne(queryWrapper);

        if (user == null) {
            log.warn("用户不存在 ! {}",username);
        }

        return new CustomUserDetail(user);
    }
}




